package com.liuxingyu.config;

import com.alibaba.fastjson.JSONObject;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author liuxingyu01
 * @date 2020-08-11-18:59
 * @description springMvc拦截器的实现
 **/
@Component
public class UserIntercetor implements HandlerInterceptor {
	
	private static Logger log = LoggerFactory.getLogger(UserIntercetor.class);

	/**
	 * 进入controller层之前拦截请求 返回值：表示是否将当前的请求拦截下来 false：拦截请求，请求别终止。true：请求不被拦截，继续执行
	 * Object obj:表示被拦的请求的目标对象（controller中方法）
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws IOException {
		String user_id = (String) request.getSession().getAttribute("session_user");
		if (log.isDebugEnabled()) {
			log.debug("UserIntercetor--preHandle--user_id=" + user_id);
		}
		if (user_id == null || "".equals(user_id)) {
			JSONObject data = new JSONObject();
			data.put("code", "10106");
			data.put("message", "未登陆或会话已失效！");
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.write(data.toString());
			out.close();
			return false;
		}

		return true;
	}

	/**
	 * 处理请求完成后视图渲染之前的处理操作 通过ModelAndView参数改变显示的视图，或发往视图的方法
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
		// System.out.println("执行了postHandle方法");
	}

	/**
	 * 视图渲染之后的操作
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// System.out.println("执行到了afterCompletion方法");
	}

}
